package com.chuangmei.com.arindoorlocationsystem.base.adapter;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

/**
 * 项目名称：ARIndoorLocationSystem
 * 类描述：RecyclerView适配器
 * 创建人：LuoHao
 * 创建时间：2018/4/8 10:55
 * 修改人：LuoHao
 * 修改时间：2018/4/8 10:55
 * 修改备注：
 */

public class BaseRecyclerViewAdapter<T> extends RecyclerView.Adapter<BaseRecyclerViewHolder> {
    private List<T> mList = new ArrayList<>();
    private int layoutId;
    private OnItemClickListener onItemClickListener;
    private BaseRecyclerViewHolder myViewHolder;

    public BaseRecyclerViewAdapter(int layoutId, List<T> list) {
        this.layoutId = layoutId;
        this.mList = list;
    }

    //onCreateViewHolder用来给rv创建缓存
    @Override
    public BaseRecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //参数3 判断条件 true  1.打气 2.添加到paraent
        // false 1.打气 （参考parent的宽度）
        View view = LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false);
        myViewHolder = new BaseRecyclerViewHolder(view);
        return myViewHolder;
    }

    //onBindViewHolder给缓存控件设置数据
    @Override
    public void onBindViewHolder(BaseRecyclerViewHolder holder, final int position) {
        T item = mList.get(position);
        convert(holder, item);

        if (onItemClickListener != null) {
            //条目的点击事件
            myViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onItemClickListener.onClick(position);
                }
            });
            //条目的长按监听，手指抬起还会触发一次点击事件
            myViewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    onItemClickListener.onLongClick(position);
                    return false;
                }
            });
        }
    }

    //子类重写改变条目值
    protected void notifyData(List<T> list) {
        mList.clear();
        mList = list;
        notifyDataSetChanged();
    }

    //子类重写填充条目值
    protected void convert(BaseRecyclerViewHolder holder, T itemMessage) {
        //什么都没有做，由子类从写填充控件数据
    }

    //获取记录数据
    @Override
    public int getItemCount() {
        return mList.size();
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public interface OnItemClickListener {
        void onClick(int position);

        void onLongClick(int position);
    }
}
